using System;
using System.Collections.Generic;
using log4net;
using MPMovieCatalog.Exception;

namespace MPMovieCatalog.Util.Grabber
{
	public class Fetcher : IWorkable
	{
        private static readonly ILog log = LogManager.GetLogger(typeof(Fetcher));

        private ProgressWorker m_progressWorker;

        public Fetcher(List<IFetchable> moviesToFetch)
        {
            MoviesToFetch = moviesToFetch;
        }

        public List<IFetchable> MoviesToFetch { get; set; }

        public string Title
        {
            get { return ResourceUtils.GetString("fetch", 3); }
        }
        
        public bool IsCancelled { get; set; }

        public string DoWork(ProgressWorker worker)
        {
            try
            {
                m_progressWorker = worker;
                Fetch();
                return ResourceUtils.GetString("fetch", 1);
            }
            catch (System.Exception e)
            {
                log.Error(string.Format("Error searching movies, message: {0}", e.Message), e);
                throw new MPMovieCatalogException(ResourceUtils.GetString("fetch", 2), e);
            }
        }

        protected void OnProgress(int step, int itemNumber, string itemName)
        {
            double percent = step;
            percent = percent / MoviesToFetch.Count * 100.0;

            string itemNameToShow = (itemName != null && itemName.Length > 40) ? itemName.Substring(0, 36) + "..." : itemName;

            m_progressWorker.OnProgress(int.Parse(Math.Floor(percent).ToString()), string.Format(ResourceUtils.GetString("fetch", 0), itemNameToShow, itemNumber.ToString(), MoviesToFetch.Count));
        }

        protected bool CancellationPending
        {
            get
            {
                return m_progressWorker.CancellationPending;
            }
        }


        protected void Fetch()
        {
        	int step = 0;
            int itemNumber = 1;
            foreach (IFetchable fetchable in MoviesToFetch)
        	{
                if (CancellationPending)
                {
                    IsCancelled = true;
                    break;
                }

                OnProgress(step++, itemNumber, fetchable.Title);
        		
        		fetchable.FetchedMovies.Clear();
	            foreach (KeyValuePair<string, List<FetchedMovie>> pair in FetcherUtils.FindMovie(fetchable.Title))
	            {
                    fetchable.FetchedMovies.AddRange(pair.Value);
	            }

                OnProgress(step, itemNumber++, fetchable.Title);
        	}
        	
        }
	}
}
